<template>
  <div>
    <!-- 查询区域 -->
    <a-card class="card-header">
      <a-form-model ref="modelForm" :model="model" :rules="rules">
        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="processNum"
              label="加工单号"
            >
              <a-input
                :disabled="disabled"
                placeholder="请输入加工单号"
                v-model.trim="model.processNum"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="planId"
              label="生产计划"
            >
              <a-select
                :disabled="disabled"
                :open="false"
                :defaultOpen="false"
                mode="multiple"
                :allowClear="true"
                placeholder="生产计划"
                v-model.trim="model.planId"
                @dropdownVisibleChange="
                  (open) =>
                    handleTableSelect(open, 'planId', 'tableModal', '生产计划')
                "
                @change="(value) => handleChange(value, 'planId', planModel)"
              >
                <a-select-option
                  v-for="item in planModel.tableOption"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.planNum }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="productionQuantity"
              label="加工单数量"
            >
              <a-input-number
                :disabled="disabled"
                style="width:100%"
                placeholder="请输入加工单数量"
                v-model.trim="model.productionQuantity"
                :min="1"
                :max="maxQuanCount"
                @change="handleSearch"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="workTeam"
              label="班次"
            >
              <a-select
                :disabled="disabled"
                :open="false"
                :defaultOpen="false"
                mode="multiple"
                :allowClear="true"
                placeholder="请选择班次"
                v-model.trim="model.workTeam"
                @dropdownVisibleChange="
                  (open) =>
                    handleTableSelect(
                      open,
                      'workTeam',
                      'tableTeamModal',
                      '班次'
                    )
                "
                @change="(value) => handleChange(value, 'workTeam', teamModel)"
              >
                <a-select-option
                  v-for="item in teamModel.tableOption"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.teamName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="billTime"
              label="工单时间"
            >
              <a-range-picker
                v-model.trim="model.billTime"
                :placeholder="['开始时间', '结束时间']"
                @change="onChange"
                format="YYYY-MM-DD "
              />
            </a-form-model-item>
          </a-col>

          <a-col :span="6">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="remark"
              label="备注"
            >
              <a-input placeholder="请输入备注" v-model.trim="model.remark" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>

    <!-- 表格区域 -->
    <a-card class="card-content">
      <a-tabs default-active-key="1">
        <a-tab-pane
          v-for="item in tabOption"
          :tab="item.label"
          :key="item.value"
        >
          <a-table
            v-if="item.value == 1"
            :columns="workColumns"
            :data-source="workTableData"
            :loading="loading"
            :pagination="false"
            :rowKey="(record, index) => record.id"
          >
          </a-table>

          <a-table
            v-if="item.value == 2"
            :columns="orderColumns"
            :data-source="goodTableData"
            :loading="loading"
            :pagination="false"
            :rowKey="(record, index) => index"
          >
            <template
              v-if="!routeQuery"
              slot="existingQuantity"
              slot-scope="text, record"
            >
              <div
                :style="{
                  color:
                    record.existingQuantity < record.planDemandQuantityNum
                      ? 'red'
                      : '#000',
                }"
              >
                {{
                  record.existingQuantity == null ? 0 : record.existingQuantity
                }}
              </div>
            </template>
          </a-table>

          <a-table
            v-if="item.value == 3"
            :columns="goodColumns"
            :data-source="CommodityList"
            :loading="loading"
            :pagination="false"
            :rowKey="(record, index) => index"
          >
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </a-card>

    <!-- 加工单生产计划选择 -->
    <TableSelectModal
      :columns="planModel.columns"
      :replaceFields="planModel.replaceFields"
      :tableKey="planModel.tableKey"
      :name="planModel.name"
      :filename="planModel.filename"
      :code="planModel.code"
      ref="tableModal"
      @tableSelect="tableSelect"
    ></TableSelectModal>

    <!-- 班次选择 -->
    <TableSelectModal
      :replaceFields="teamModel.replaceFields"
      :columns="teamModel.columns"
      :tableKey="teamModel.tableKey"
      :name="teamModel.name"
      :filename="teamModel.filename"
      ref="tableTeamModal"
      @tableSelect="tableTeamSelect"
    ></TableSelectModal>

    <div class=" footer-btn">
      <a-button type="primary" @click="handleSubmit">保存</a-button>
    </div>
  </div>
</template>

<script>
import {
  workColumns,
  orderAddColumns,
  orderEditColumns,
  planModel,
  teamModel,
  goodColumns,
} from "./components/tableConfig";
import api from "@/api/apiServer";
import moment from "moment";
import TableSelectModal from "@/components/TableSelectModal";

export default {
  components: {
    TableSelectModal,
  },
  data() {
    let validatePass = (rule, value, callback) => {
      if (value > this.maxQuanCount) {
        callback(new Error("加工单数量已超过最大值"));
      } else {
        if (value === null || value === undefined || value === "") {
          callback(new Error("请输入加工单数量"));
        } else {
          callback();
        }
      }
    };
    return {
      workColumns,
      goodColumns,
      labelCol: {
        xl: { span: 8 },
        xxl: { span: 8 },
      },
      wrapperCol: {
        xl: { span: 16 },
        xxl: { span: 16 },
      },
      model: {
        bomWorkStageList: [],
        planMaterial: [], // 用料
      },
      tabOption: [
        { label: "加工工序", value: 1 },
        { label: "计划用料", value: 2 },
        { label: "商品信息", value: 3 },
      ],
      workTableData: [], // 工序列表
      goodTableData: [], // 用料列表
      CommodityList: [], // 商品信息
      tableData: [],
      selectedRowKeys: [],
      selectedGoodRowKeys: [],
      loading: false,
      maxQuanCount: 99999,
      planModel,
      teamModel,
      disabled: false,
      validatePass,
      orderColumns: [],
    };
  },
  computed: {
    rules() {
      return {
        processNum: [
          { required: true, message: "请输入加工单号", trigger: "change" },
        ],
        planId: [
          { required: true, message: "请选择生产计划", trigger: "blur" },
        ],
        productionQuantity: [
          {
            validator: this.validatePass,
          },
          { required: true, message: "请输入加工单数量", trigger: "change" },
        ],
        workTeam: [
          { required: true, message: "请选择班次", trigger: "change" },
        ],
        billTime: [
          { required: true, message: "请选择工单时间", trigger: "change" },
        ],
      };
    },
    routeQuery() {
      return this.$route.query.id;
    },
  },
  mounted() {
    if (this.$route.query.id) {
      this.getDetail(this.$route.query.id);
      this.disabled = true;
      this.orderColumns = orderEditColumns;
    } else {
      this.$set(
        this.model,
        "processStartTime",
        moment(new Date())
          .subtract(0, "days")
          .format("YYYY-MM-DD")
      );
      this.orderColumns = orderAddColumns;
      this.disabled = false;
      this.getWorksheetNum();
    }
  },
  methods: {
    moment,
    disabledDate(currentDate) {
      return currentDate && currentDate < moment(this.model.processStartTime);
    },
    // 获取商品信息
    async getCommodityList(id) {
      let params = {
        pageNumber: 1,
        pageSize: 10,
        id,
        deleteFlag: "N",
      };
      const res = await api.CommodityList(params);
      this.CommodityList = res.data.data;
    },
    // 获取所有的生产计划
    async getProductPlanFindPlan() {
      const params = {
        id: this.model.planId,
        deleteFlag: "N",
        pageNumber: 1,
        pageSize: 10,
      };
      const res = await api.ProductPlanFindPlan(params);
      this.$set(this.planModel, "tableOption", res.data.data);
      this.$forceUpdate();
    },
    // 获取bom工序
    async getProductGet(id) {
      const res = await api.ProductGet({ id });
      this.workTableData = res.data.bomWorkStageList;
    },
    // 新增时获取加工单用料
    async getWorksheetGetMaterials(planQuantity) {
      let params = {
        bomId: this.model.bomId,
        planQuantity,
      };
      if (planQuantity <= this.maxQuanCount) {
        const res = await api.WorksheetGetMaterials(params);
        this.goodTableData = res.data;
      }
    },
    // 编辑时 获取加工单计划用料
    async getWorksheetGetMaterialsPlan(worksheetId) {
      const res = await api.WorksheetGetMaterialsPlan({ worksheetId });
      this.goodTableData = res.data;
    },
    onChange(date, dateString) {
      this.$set(this.model, "processStartTime", dateString[0]);
      this.$set(this.model, "processEndTime", dateString[1]);
    },
    tableSelect(result, tableOption) {
      this.planModel.tableOption = tableOption;
      let checkResult = result[0];
      if (result.length > 0) {
        this.getProductGet(checkResult.bomId);
        this.$set(this.model, "planId", checkResult.id);
        this.$set(this.model, "bomId", checkResult.bomId);
        this.$set(this.model, "planNum", checkResult.planNum);
        this.$set(this.model, "goodsId", checkResult.goodsId);
        this.$refs.modelForm.clearValidate(["planId"]);
        this.getCommodityList(checkResult.goodsId);
      } else {
        delete this.model.planId;
        this.$set(this.model, "bomId", "");
        this.$set(this.model, "planNum", "");
        this.$set(this.model, "goodsId", "");
      }

      if (this.model.planNum) {
        this.getWorksheetGetRemain(this.model.planNum);
      }
    },
    tableTeamSelect(result, tableOption) {
      this.teamModel.tableOption = tableOption;
      let checkResult = result[0];
      this.$set(this.model, "workTeam", checkResult.id);
      this.$refs.modelForm.clearValidate(["workTeam"]);
    },
    // 查询加工单剩余数量
    async getWorksheetGetRemain(planNum) {
      const res = await api.WorksheetGetRemain({ planNum });
      this.$set(this.model, "productionQuantity", res.data);
      this.maxQuanCount = res.data;
      this.getWorksheetGetMaterials(res.data);
    },
    // 选择框点击事件
    handleTableSelect(open, key, refName, name) {
      this.$refs[refName].title = name;
      this.$refs[refName].modalAdd();
      if (this.model[key]) {
        let arr = this.model[key].toString().split(",");
        if (arr.length > 0) {
          let newArr = arr.map((item) => {
            return Number(item);
          });
          this.$refs[refName].selectedRowKeys = newArr;
        } else {
          this.$refs[refName].selectedRowKeys = [];
        }
      }
    },
    // 事件选择回调
    handleChange(value, key, model) {
      if (value.length > 0) {
        if (model.mode) {
          this.model[key] = value;
        } else {
          this.model[key] = value.toString();
        }
      } else {
        delete this.model[key];
      }
    },
    // 获取加工单号
    async getWorksheetNum() {
      const res = await api.ProductPlanNum({ type: "parent", code: "JGD" });
      this.$set(this.model, "processNum", res.data);
    },
    // 获取详情页数据
    async getDetail(worksheetId) {
      const res = await api.WorksheetDetail({ worksheetId });
      this.model = Object.assign({}, res.data.detile);
      if (res.data.detile.planId) {
        this.getProductPlanFindPlan();
      }
      this.workTableData = res.data.detile.bomWorkStageList;
      if (this.workTableData && this.workTableData.length > 0) {
        this.workTableData.forEach((item) => {
          this.selectedRowKeys.push(item.id);
        });
      }
      this.getWorksheetGetMaterialsPlan(worksheetId);
      this.getCommodityList(this.model.goodsId);
      if (this.model.processStartTime && this.model.processEndTime) {
        this.$set(this.model, "billTime", [
          moment(this.model.processStartTime).format("YYYY-MM-DD"),
          moment(this.model.processEndTime).format("YYYY-MM-DD"),
        ]);
      }

      this.$forceUpdate();
    },
    // 输入事件
    handleSearch(value) {
      if (
        value !== 0 &&
        this.model.bomId &&
        value !== "" &&
        value !== undefined &&
        value !== null
      ) {
        this.getWorksheetGetMaterials(value);
        this.goodTableData = [];
      }
    },
    handleSubmit() {
      const that = this;
      this.$refs.modelForm.validate((valid) => {
        if (valid) {
          that.submitVulFun();
        } else {
          return false;
        }
      });
    },
    async submitVulFun() {
      if (this.model.productionQuantity > 0) {
        const res = await api.WorksheetUpdate(this.model);
        if (res.code && res.code !== 200) {
          this.$message.error(res.message);
          this.confirmLoading = false;
          return;
        }
        this.$message.success(res.message);
        this.confirmLoading = false;
        this.model = Object.assign({});
        this.$router.go(-1);
      } else {
        this.$message.error("生产计划数量已完成");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.card-header {
  margin: 20px 0;
}
button {
  margin-right: 13px;
}
.card-content {
  margin-bottom: 20px;
  .contetnBox {
    border: 1px solid #ebedf0;
    border-radius: 2px;
    padding: 20px 0;
    .headerBox {
      padding: 0 20px;
    }
  }
}
.ant-form-item {
  margin: 10px 0;
}
.tableSpan {
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: 600;
  color: #1a5eff;
}

.footer-btn {
  width: 100%;
  text-align: center;
  margin: 37px 0;
  button {
    width: 200px;
    height: 40px;
    background: #1a5eff;
    border-radius: 2px;
  }
}
</style>
